package com.lych.server.service;

import cn.hutool.core.collection.CollUtil;
import com.lych.autoconfig.template.HuanXinTemplate;
import com.lych.autoconfig.template.SmsTemplate;
import com.lych.commons.utils.Constants;
import com.lych.commons.utils.JwtUtils;
import com.lych.dubbo.api.*;
import com.lych.model.domain.User;
import com.lych.model.domain.UserInfo;
import com.lych.model.mongo.Friend;
import com.lych.model.mongo.SoulUser;
import com.lych.model.mongo.UserLike;
import com.lych.model.mongo.Visitors;
import com.lych.model.vo.CountsVo;
import com.lych.model.vo.ErrorResult;
import com.lych.model.vo.PageResult;
import com.lych.model.vo.StatisticsVo;
import com.lych.server.exception.BusinessException;
import com.lych.server.interceptor.UserHolder;
import javafx.util.Duration;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.checkerframework.checker.units.qual.A;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.lang.reflect.Array;
import java.util.*;

@Service
public class UserService {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    @Autowired
    private UserFreezeService userFreezeService;

    @Autowired
    private MqMessageService mqMessageService;


    /**
     * 发送验证码
     * @param phone
     */
    public void sendMsg(String phone){
        //根据手机号查询用户,如果用户存在，查看是否被冻结
        User user = userApi.findByMobile(phone);
        if (user != null) {
            userFreezeService.CheckUserStatus("1",user.getId());
        }
        //随机生成6为数为验证码
        //String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        //发短信
        //smsTemplate.sendSms(phone,code);
        //将验证码存入redis
        redisTemplate.opsForValue().set("CODE_" + phone, code, java.time.Duration.ofSeconds(300));
    }

    /**
     * 登录验证
     * @param phone
     * @param code
     * @return
     */
    public Map loginloginVerification(String phone, String code) {
        //从redis获得验证码
        String rediscode = redisTemplate.opsForValue().get("CODE_" + phone);
        //对验证码校验
        if (StringUtils.isEmpty(rediscode) || !code.equals(rediscode)){
            throw new BusinessException(ErrorResult.loginError());
        }
        //删除redis中的验证码
        redisTemplate.delete("CODE_" + phone);
        //通过手机号码查询用户
        User user = userApi.findByMobile(phone);
        //如果用户不存在，创建用户保存到数据库
        String type = "0101";//登录
        boolean isNew = false;
        if (user == null) {
            type = "0102";//注册
            user = new User();
            user.setMobile(phone);
            user.setCreated(new Date());
            user.setUpdated(new Date());
            user.setPassword(String.valueOf(DigestUtils.md5Digest("123456".getBytes())));
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;

            //注册环信用户
            String hxUser = "hx" + user.getId();
            Boolean aBoolean = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            //如果注册成功，将信息添加到User表中
            if (aBoolean) {
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }
        }

        //发送消息
        mqMessageService.sendLogService(user.getId(),type,"user",null);

        //通过JWT生成token
        Map tokenMap = new HashMap();
        tokenMap.put("id",user.getId());
        tokenMap.put("mobile",phone);
        String token = JwtUtils.getToken(tokenMap);

        //返回
        Map retMap = new HashMap();
        retMap.put("token",token);
        retMap.put("isNew",isNew);
        return retMap;
    }

    /**
     * 修改手机号 - 2 校验验证码
     * @param code
     * @return
     */
    public Boolean phoneCheckVerificationCode(String code) {
        //拿到用户当前手机号
        String phone = UserHolder.getMobile();
        String rediscode = redisTemplate.opsForValue().get("CODE_" + phone);
        if (StringUtils.isEmpty(rediscode) || !code.equals(rediscode)){
            return false;
        }
        //删除redis中的验证码
        redisTemplate.delete("CODE_" + phone);

        return true;
    }

    /**
     * 修改手机号 - 3 保存
     * @param user
     */
    public void updatePhone(User user) {
        userApi.updatePhone(user);
    }

    /**
     * 互相喜欢，喜欢，粉丝 - 统计
     * like 喜欢
     * beLike 粉丝
     * fallInLove 互相喜欢
     * @return
     */
    public CountsVo counts() {
        Integer like = redisTemplate.opsForSet().size(Constants.USER_LIKE_KEY + UserHolder.getUserId()).intValue();
        Integer beLike = userLikeApi.findById(UserHolder.getUserId());
        Integer fallInLove = 0;
        Set<String> members = redisTemplate.opsForSet().members(Constants.USER_LIKE_KEY + UserHolder.getUserId());
        for (String member : members) {
            if (redisTemplate.opsForSet().isMember(Constants.USER_LIKE_KEY + member, UserHolder.getUserId().toString())) {
                fallInLove++;
            }
        }
        return new CountsVo(fallInLove,like,beLike);
    }

    /**
     * 互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
     * @param type
     * @param page
     * @param pagesize
     * @param nickname
     * @return
     */
    public PageResult friendsType(Integer type, Integer page, Integer pagesize, String nickname) {
        List<Long> fallInLoves = new ArrayList<>(); //用户id
        Map<Long, UserInfo> infoMap = new HashMap<>();  //用户详细信息
        switch (type){
            case 1:
                //互相关注
                Long userId1 = UserHolder.getUserId();
                //调用api，查询我喜欢的用户id
                List<Long> likeList = userLikeApi.findLikeById(userId1,page,pagesize);
                //跟据id查询是否相互喜欢。
                fallInLoves = userLikeApi.fallInLove(likeList,userId1,page,pagesize);
                if (fallInLoves.size() == 0){
                    return new PageResult();
                }
                //根据id查询详细信息
                infoMap = userInfoApi.findByIds(fallInLoves, null);

                break;
            case 2:
                //我关注
                Long userId2 = UserHolder.getUserId();
                //调用api，查询我喜欢的用户id
                fallInLoves = userLikeApi.findLikeById(userId2,page,pagesize);
                if (fallInLoves.size() == 0){
                    return new PageResult();
                }
                //根据id查询详细信息
                infoMap = userInfoApi.findByIds(fallInLoves, null);

                break;
            case 3:
                //粉丝
                Long userId3 = UserHolder.getUserId();
                //调用api，查询谁喜欢我,得到id
                fallInLoves = userLikeApi.likeMe(userId3,page,pagesize);
                if (fallInLoves.size() == 0){
                    return new PageResult();
                }
                //根据id查询详细信息
                infoMap = userInfoApi.findByIds(fallInLoves, null);
                break;
            case 4:
                //谁看过我
                String key = Constants.VISITORS;
                String hashKey = String.valueOf(UserHolder.getUserId());
                //得到看过我的id
                Long date = null;
                try {
                    date = (Long) redisTemplate.opsForHash().get(key, hashKey);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                //删除redis中的数据
                redisTemplate.opsForHash().delete(key,hashKey);

                if (date == null) {
                    date = 0L;
                }
                fallInLoves = visitorsApi.findByUserId(date,UserHolder.getUserId(),page,pagesize);
                if (fallInLoves.size() == 0){
                    return new PageResult();
                }
                //根据id查询详细信息
                infoMap = userInfoApi.findByIds(fallInLoves, null);

                //将最后访问我的时间存入redis
                Visitors visitors = visitorsApi.findById(fallInLoves.get(0),UserHolder.getUserId());
                redisTemplate.opsForHash().put(key,hashKey,visitors.getDate().toString());

                break;
        }
        //根据id查询缘分值
        List<Visitors> list = visitorsApi.findScoreByIds(UserHolder.getUserId(),fallInLoves); //缘分值
        Map<Object, Visitors> fieldValueMap = CollUtil.fieldValueMap(list, "visitorUserId");
        //构造对象返回
        List<StatisticsVo> vos = new ArrayList<>();
        //构造返回总数
        int size = fallInLoves.size();
        for (Long i: fallInLoves) {
            UserInfo userInfo = infoMap.get(i);
            Visitors visitors = fieldValueMap.get(i);
            StatisticsVo vo = StatisticsVo.init(userInfo,visitors);
            vos.add(vo);
        }
        return new PageResult(page,pagesize,size,vos);
    }
}
